package org.easy.core.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.easy.core.dto.JwtDataDto;
import org.easy.core.exception.UtilException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;


public class JwtUtil {


    public static String createToken(JwtDataDto userinfo, long expirationDay, String secretKey) {
        String jsonString = JSON.toJSONString(userinfo);
        return getCompact(jsonString, expirationDay, secretKey);
    }

    public static String createToken(JwtDataDto userinfo, String secretKey) {
        String jsonString = JSON.toJSONString(userinfo);
        return getCompact(jsonString, 1000 * 60 * 60 * 24 * 15L, secretKey);
    }

    public static String getCompact(String jsonString, long expirationDay, String secretKey) {
        return Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * expirationDay))
                .signWith(SignatureAlgorithm.HS256, secretKey.getBytes(StandardCharsets.UTF_8))
                .claim("s", jsonString)
                .compact();
    }


    public static Claims parseToken(String token, String secretKey) {
        return parseToken(token, secretKey.getBytes(StandardCharsets.UTF_8));
    }

    public static Claims parseToken(String token, byte[] secretKey) {
        try {
            return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            throw new UtilException(e);
        }
    }

    public static JwtDataDto getUser(String token) {
        Claims claims = parseToken(token, "");
        String data = claims.get("s", String.class);
        return JSONObject.parseObject(data, JwtDataDto.class);
    }

    public static Long getUserId(String token) {
        return getUser(token).getUserId();
    }

    public static Long getStaffId(String token) {
        return getUser(token).getStaffId();
    }


}